# _*_ coding: utf-8 _*_
from odoo import models, api, registry, tools
from odoo.tools import float_compare
import threading
import logging

_logger = logging.getLogger(__name__)


class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    @api.multi
    def _action_procurement_create(self):
        """
        Create procurements based on quantity ordered. If the quantity is increased, new
        procurements are created. If the quantity is decreased, no automated action is taken.
        """
        precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
        proc_vals = []
        sale_order = self.mapped("order_id")
        assert len(sale_order) == 1, u"订单明细行不能来自多个销售订单"
        if not sale_order.procurement_group_id:
            vals = sale_order._prepare_procurement_group()
            sale_order.procurement_group_id = self.env["procurement.group"].create(vals)
        for line in self:
            if line.state != 'sale' or not line.product_id._need_procurement():
                continue
            qty = 0.0
            for proc in line.procurement_ids:
                qty += proc.product_qty
            if float_compare(qty, line.product_uom_qty, precision_digits=precision) >= 0:
                continue

            vals = line._prepare_order_line_procurement(group_id=sale_order.procurement_group_id.id)
            vals['product_qty'] = line.product_uom_qty - qty
            proc_vals.append(vals)
        sale_order.procurement_group_id.with_context(procurement_autorun_defer=True).write({
            "procurement_ids": [(0, 0, val) for val in proc_vals]
        })
        if len(self) <= 30:
            sale_order.procurement_group_id.procurement_ids.run()
        else:
            sale_order.env.cr.commit()
            self.procure_calculation_sale_sync(sale_order.procurement_group_id.procurement_ids)
        return sale_order.procurement_group_id.procurement_ids

    @api.model
    def procure_calculation_sale(self, procurement_ids):
        with api.Environment.manage():
            new_cr = registry(self._cr.dbname).cursor()
            self = self.with_env(self.env(cr=new_cr))
            procurements = self.env['procurement.order'].browse(procurement_ids)
            procurements.run(autocommit=True)
            self._cr.commit()
            self._cr.close()
            return {}

    @api.multi
    def procure_calculation_sale_sync(self, procurements):
        threaded_calculation = threading.Thread(target=self.procure_calculation_sale, args=(procurements.ids,))
        threaded_calculation.start()
        return True
